﻿using System.Data.Common;
using System.Data.SqlServerCe;
using System.Windows;
using System.Windows.Data;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using System.ComponentModel;
using System;
using System.Data;
using System.Data.Objects;
using System.Xml.Linq;
using System.Configuration;
using Microsoft.Win32;

namespace AppTrans
{
    public partial class MainWindow : Window
    {
          db_trans3Entities database;

        public MainWindow()
        {
            InitializeComponent();
            InitializeData();
        }
        private void InitializeData()
        {
            database = new db_trans3Entities();
            MainPanel.DataContext = database;

            CheckVersionBD();
            
            //Запись в реестр Windows даты и времени входа в систему.
            RegistryKeyValues.SetValue("LastStartProgram", DateTime.Now.ToString());

            //Работа - Продажа + Доставка
            WorksDataGrid.ItemsSource = from w in database.Works
                                        where w.OperType == 1
                                        orderby w.Date
                                        select w;

            //Работа - Закупка на склад
            WorksDataGrid5.ItemsSource = from w in database.Works
                                        where w.OperType == 5
                                        orderby w.Date
                                        select w;

            //Работа - Продажа со склада
            WorksDataGrid6.ItemsSource = from w in database.Works
                                        where w.OperType == 6
                                        orderby w.Date
                                        select w;

            //Работа - Перевозки
            WorksDataGrid2.ItemsSource = from w2 in database.Works
                                         where w2.OperType == 2
                                         orderby w2.Date
                                         select w2;

            //Работа - Продажа
            WorksDataGrid3.ItemsSource = from w3 in database.Works
                                        where w3.OperType == 3
                                        orderby w3.Date
                                        select w3;

            //Работа - Услуги
            WorksDataGrid4.ItemsSource = from w4 in database.Works
                                         where w4.OperType == 4
                                         orderby w4.Date
                                         select w4;
            
            //Работа - Техн. режим
            WorksDataGrid9.ItemsSource = from w9 in database.Works
                                        orderby w9.Date
                                        select w9;

            TransactionsDataGrid.ItemsSource = from t in database.Transactions
                                               orderby t.Date
                                               select t;
            
            RefuelingDataGrid.ItemsSource =    from r in database.Refuelings //Заправка своя АЗС
                                               where r.FuelOperType == 1
                                               orderby r.Date
                                               select r;

            RefuelingDataGrid2.ItemsSource = from r2 in database.Refuelings //Заправка у постащика
                                             where r2.FuelOperType == 2
                                             orderby r2.Date
                                             select r2;

            //Справочники для полей типа ComboBox таблицы Refueling
            RefuelingFuelOperTypeList.ItemsSource = from DictionaryFuelOperTypes in database.DictionaryFuelOperTypes
                                            where DictionaryFuelOperTypes.Id == 1
                                            orderby DictionaryFuelOperTypes.Id
                                            select new { DictionaryFuelOperTypes.Id, DictionaryFuelOperTypes.Name };

            RefuelingGasSattionsList.ItemsSource = from DictionaryGasStations in database.DictionaryGasStations
                                                   where DictionaryGasStations.View == 1
                                                   orderby DictionaryGasStations.Name
                                                   select new
                                                   {
                                                       Id = DictionaryGasStations.Id,
                                                       Name = DictionaryGasStations.Name
                                                   };

            RefuelingsMachineList.ItemsSource = from DictionaryMachines in database.DictionaryMachines
                                                orderby DictionaryMachines.Name
                                                where DictionaryMachines.View == 1
                                                select new
                                                {
                                                    Id = DictionaryMachines.Id,
                                                    Name = DictionaryMachines.Name
                                                };

            RefuelingDriverList.ItemsSource = from DictionaryDrivers in database.DictionaryDrivers
                                                orderby DictionaryDrivers.Name
                                                where DictionaryDrivers.View == 1
                                                select DictionaryDrivers;

            RefuelingsFuelList.ItemsSource = from DictionaryCategories in database.DictionaryCategories
                                             orderby DictionaryCategories.DictionaryTransactionType.Id
                                             where DictionaryCategories.View == 1 && DictionaryCategories.Fuel == 1
                                             select new
                                             {
                                                 Id = DictionaryCategories.Id,
                                                 Name = DictionaryCategories.Name
                                             };

            RefuelingsProjectList.ItemsSource = from DictionaryProjects in database.DictionaryProjects
                                                orderby DictionaryProjects.Name
                                                where DictionaryProjects.View == 1
                                                select new
                                                {
                                                    Id = DictionaryProjects.Id,
                                                    Name = DictionaryProjects.Name
                                                };

            //Справочники для полей типа ComboBox таблицы Refueling2 - заправка у поставщика
            RefuelingFuelOperTypeList2.ItemsSource = from DictionaryFuelOperTypes in database.DictionaryFuelOperTypes
                                                    where DictionaryFuelOperTypes.Id == 2
                                                    orderby DictionaryFuelOperTypes.Id
                                                    select new { DictionaryFuelOperTypes.Id, DictionaryFuelOperTypes.Name };

            RefuelingFuelSupplierList2.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                            orderby DictionaryPartners.Name
                                            where DictionaryPartners.View == 1 || DictionaryPartners.FuelSupplier == 1
                                            select DictionaryPartners;

            RefuelingFuelTypeList2.ItemsSource = from DictionaryFuelType in database.DictionaryFuelTypes
                                                where DictionaryFuelType.View == 1
                                                orderby DictionaryFuelType.Name
                                                select new
                                                {
                                                    Id = DictionaryFuelType.Id,
                                                    Name = DictionaryFuelType.Name
                                                };

            RefuelingsMachineList2.ItemsSource = from DictionaryMachines in database.DictionaryMachines
                                                orderby DictionaryMachines.Name
                                                where DictionaryMachines.View == 1
                                                select new
                                                {
                                                    Id = DictionaryMachines.Id,
                                                    Name = DictionaryMachines.Name
                                                };
            
            RefuelingDriverList2.ItemsSource = from DictionaryDrivers in database.DictionaryDrivers
                                          orderby DictionaryDrivers.Name
                                          where DictionaryDrivers.View == 1
                                          select DictionaryDrivers;


            RefuelingsProjectList2.ItemsSource = from DictionaryProjects in database.DictionaryProjects
                                                orderby DictionaryProjects.Name
                                                where DictionaryProjects.View == 1
                                                select new
                                                {
                                                    Id = DictionaryProjects.Id,
                                                    Name = DictionaryProjects.Name
                                                };

            //Справочники для полей типа ComboBox таблицы Works 1 - Закладка "Продажа+Доставка"

            WorksOperTypeList.ItemsSource = from DictionaryOperTypes in database.DictionaryOperTypes
                                            where DictionaryOperTypes.Id == 1
                                            orderby DictionaryOperTypes.Id
                                            select new { DictionaryOperTypes.Id, DictionaryOperTypes.Name };

            WorksLoadingPlaceList.ItemsSource = from DictionaryPlaces in database.DictionaryPlaces
                                                where DictionaryPlaces.View == 1
                                                orderby DictionaryPlaces.Name
                                                select DictionaryPlaces;

            WorksUnloadingPlaceList.ItemsSource = from DictionaryPlaces in database.DictionaryPlaces
                                                  where DictionaryPlaces.View == 1
                                                  orderby DictionaryPlaces.Name
                                                  select DictionaryPlaces;

            WorksMachineList.ItemsSource = from DictionaryMachines in database.DictionaryMachines
                                           orderby DictionaryMachines.Name
                                           where DictionaryMachines.View == 1
                                           select DictionaryMachines;

            WorksDriverList.ItemsSource = from DictionaryDrivers in database.DictionaryDrivers
                                          orderby DictionaryDrivers.Name
                                          where DictionaryDrivers.View == 1
                                          select DictionaryDrivers;

            WorksGoodsList.ItemsSource = from DictionaryGoods in database.DictionaryGoods
                                         orderby DictionaryGoods.Name
                                         where DictionaryGoods.View == 1
                                         select DictionaryGoods;

            WorksSupplierList.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                            orderby DictionaryPartners.Name
                                            where DictionaryPartners.View == 1 || DictionaryPartners.Supplier == 1
                                            select DictionaryPartners;

            WorksCurrencyPurchasingList.ItemsSource = from DictionaryCurrencies in database.DictionaryCurrencies
                                                      orderby DictionaryCurrencies.Name
                                                      where DictionaryCurrencies.View == 1
                                                      select DictionaryCurrencies;

            WorksSupplierCommissionList.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                                      orderby DictionaryPartners.Name
                                                      where DictionaryPartners.View == 1 || DictionaryPartners.SupplierCommission == 1
                                                      select DictionaryPartners;

            WorksCustomerList.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                            orderby DictionaryPartners.Name
                                            where DictionaryPartners.View == 1 || DictionaryPartners.Customer == 1
                                            select DictionaryPartners;

            WorksCurrencySalesList.ItemsSource = from DictionaryCurrencies in database.DictionaryCurrencies
                                                 orderby DictionaryCurrencies.Name
                                                 where DictionaryCurrencies.View == 1
                                                 select DictionaryCurrencies;

            WorksCustomerCommissionList.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                                      orderby DictionaryPartners.Name
                                                      where DictionaryPartners.View == 1 || DictionaryPartners.CustomerCommission == 1
                                                      select DictionaryPartners;

            WorksProjectList.ItemsSource = from DictionaryProjects in database.DictionaryProjects
                                           orderby DictionaryProjects.Name
                                           where DictionaryProjects.View == 1
                                           select DictionaryProjects;

            //Справочники для полей типа ComboBox таблицы Works 5 - Закладка "Закупка на склад"

            WorksOperTypeList5.ItemsSource = from DictionaryOperTypes in database.DictionaryOperTypes
                                            where DictionaryOperTypes.Id == 5
                                            orderby DictionaryOperTypes.Id
                                            select new { DictionaryOperTypes.Id, DictionaryOperTypes.Name };

            WorksLoadingPlaceList5.ItemsSource = from DictionaryPlaces in database.DictionaryPlaces
                                                where DictionaryPlaces.View == 1
                                                orderby DictionaryPlaces.Name
                                                select DictionaryPlaces;

            WorksUnloadingPlaceList5.ItemsSource = from DictionaryPlaces in database.DictionaryPlaces
                                                  where DictionaryPlaces.View == 1
                                                  orderby DictionaryPlaces.Name
                                                  select DictionaryPlaces;

            WorksMachineList5.ItemsSource = from DictionaryMachines in database.DictionaryMachines
                                           orderby DictionaryMachines.Name
                                           where DictionaryMachines.View == 1
                                           select DictionaryMachines;

            WorksDriverList5.ItemsSource = from DictionaryDrivers in database.DictionaryDrivers
                                          orderby DictionaryDrivers.Name
                                          where DictionaryDrivers.View == 1
                                          select DictionaryDrivers;

            WorksGoodsList5.ItemsSource = from DictionaryGoods in database.DictionaryGoods
                                         orderby DictionaryGoods.Name
                                         where DictionaryGoods.View == 1
                                         select DictionaryGoods;

            WorksSupplierList5.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                            orderby DictionaryPartners.Name
                                            where DictionaryPartners.View == 1 || DictionaryPartners.Supplier == 1
                                            select DictionaryPartners;

            WorksCurrencyPurchasingList5.ItemsSource = from DictionaryCurrencies in database.DictionaryCurrencies
                                                      orderby DictionaryCurrencies.Name
                                                      where DictionaryCurrencies.View == 1
                                                      select DictionaryCurrencies;

            WorksSupplierCommissionList5.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                                      orderby DictionaryPartners.Name
                                                      where DictionaryPartners.View == 1 || DictionaryPartners.SupplierCommission == 1
                                                      select DictionaryPartners;

            WorksProjectList5.ItemsSource = from DictionaryProjects in database.DictionaryProjects
                                           orderby DictionaryProjects.Name
                                           where DictionaryProjects.View == 1
                                           select DictionaryProjects;

            //Справочники для полей типа ComboBox таблицы Works 6 - Закладка "Продажа со склада"

            WorksOperTypeList6.ItemsSource = from DictionaryOperTypes in database.DictionaryOperTypes
                                            where DictionaryOperTypes.Id == 6
                                            orderby DictionaryOperTypes.Id
                                            select new { DictionaryOperTypes.Id, DictionaryOperTypes.Name };

            WorksLoadingPlaceList6.ItemsSource = from DictionaryPlaces in database.DictionaryPlaces
                                                where DictionaryPlaces.View == 1
                                                orderby DictionaryPlaces.Name
                                                select DictionaryPlaces;

            WorksUnloadingPlaceList6.ItemsSource = from DictionaryPlaces in database.DictionaryPlaces
                                                  where DictionaryPlaces.View == 1
                                                  orderby DictionaryPlaces.Name
                                                  select DictionaryPlaces;

            WorksMachineList6.ItemsSource = from DictionaryMachines in database.DictionaryMachines
                                           orderby DictionaryMachines.Name
                                           where DictionaryMachines.View == 1
                                           select DictionaryMachines;

            WorksDriverList6.ItemsSource = from DictionaryDrivers in database.DictionaryDrivers
                                          orderby DictionaryDrivers.Name
                                          where DictionaryDrivers.View == 1
                                          select DictionaryDrivers;

            WorksGoodsList6.ItemsSource = from DictionaryGoods in database.DictionaryGoods
                                         orderby DictionaryGoods.Name
                                         where DictionaryGoods.View == 1
                                         select DictionaryGoods;

            WorksCustomerList6.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                            orderby DictionaryPartners.Name
                                            where DictionaryPartners.View == 1 || DictionaryPartners.Customer == 1
                                            select DictionaryPartners;

            WorksCurrencySalesList6.ItemsSource = from DictionaryCurrencies in database.DictionaryCurrencies
                                                 orderby DictionaryCurrencies.Name
                                                 where DictionaryCurrencies.View == 1
                                                 select DictionaryCurrencies;

            WorksCustomerCommissionList6.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                                      orderby DictionaryPartners.Name
                                                      where DictionaryPartners.View == 1 || DictionaryPartners.CustomerCommission == 1
                                                      select DictionaryPartners;

            WorksProjectList6.ItemsSource = from DictionaryProjects in database.DictionaryProjects
                                           orderby DictionaryProjects.Name
                                           where DictionaryProjects.View == 1
                                           select DictionaryProjects;
            
            //Справочники для полей типа ComboBox таблицы Works2 - Перевозки
            
            WorksOperTypeList2.ItemsSource = from DictionaryOperTypes in database.DictionaryOperTypes
                                             where DictionaryOperTypes.Id == 2
                                             orderby DictionaryOperTypes.Name
                                             select DictionaryOperTypes;

            WorksLoadingPlaceList2.ItemsSource = from DictionaryPlaces in database.DictionaryPlaces
                                                 where DictionaryPlaces.View == 1
                                                 orderby DictionaryPlaces.Name
                                                 select DictionaryPlaces;

            WorksUnloadingPlaceList2.ItemsSource = from DictionaryPlaces in database.DictionaryPlaces
                                                   where DictionaryPlaces.View == 1
                                                   orderby DictionaryPlaces.Name
                                                   select DictionaryPlaces;

            WorksMachineList2.ItemsSource = from DictionaryMachines in database.DictionaryMachines
                                            orderby DictionaryMachines.Name
                                            where DictionaryMachines.View == 1
                                            select DictionaryMachines;
            
            WorksDriverList2.ItemsSource = from DictionaryDrivers in database.DictionaryDrivers
                                           orderby DictionaryDrivers.Name
                                           where DictionaryDrivers.View == 1
                                           select DictionaryDrivers;

            WorksGoodsList2.ItemsSource = from DictionaryGoods in database.DictionaryGoods
                                          orderby DictionaryGoods.Name
                                          where DictionaryGoods.View == 1
                                          select DictionaryGoods;

            WorksCustomerList2.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                             orderby DictionaryPartners.Name
                                             where DictionaryPartners.View == 1 || DictionaryPartners.Customer == 1
                                             select DictionaryPartners;
            
            WorksCurrencySalesList2.ItemsSource = from DictionaryCurrencies in database.DictionaryCurrencies
                                                  orderby DictionaryCurrencies.Name
                                                  where DictionaryCurrencies.View == 1
                                                  select DictionaryCurrencies;

            WorksCustomerCommissionList2.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                                       orderby DictionaryPartners.Name
                                                       where DictionaryPartners.View == 1 || DictionaryPartners.CustomerCommission == 1
                                                       select DictionaryPartners;

            WorksProjectList2.ItemsSource = from DictionaryProjects in database.DictionaryProjects
                                            orderby DictionaryProjects.Name
                                            where DictionaryProjects.View == 1
                                            select DictionaryProjects;
            
            //Справочники для полей типа ComboBox таблицы Works3 - Закладка "Продажа"

            WorksOperTypeList3.ItemsSource = from DictionaryOperTypes in database.DictionaryOperTypes
                                             where DictionaryOperTypes.Id == 3
                                             orderby DictionaryOperTypes.Name
                                             select DictionaryOperTypes;

            WorksGoodsList3.ItemsSource = from DictionaryGoods in database.DictionaryGoods
                                          orderby DictionaryGoods.Name
                                          where DictionaryGoods.View == 1
                                          select DictionaryGoods;

            WorksSupplierList3.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                            orderby DictionaryPartners.Name
                                            where DictionaryPartners.View == 1 || DictionaryPartners.Supplier == 1
                                            select DictionaryPartners;

            WorksCurrencyPurchasingList3.ItemsSource = from DictionaryCurrencies in database.DictionaryCurrencies
                                                      orderby DictionaryCurrencies.Name
                                                      where DictionaryCurrencies.View == 1
                                                      select DictionaryCurrencies;

            WorksSupplierCommissionList3.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                                      orderby DictionaryPartners.Name
                                                      where DictionaryPartners.View == 1 || DictionaryPartners.SupplierCommission == 1
                                                      select DictionaryPartners;

            WorksCustomerList3.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                            orderby DictionaryPartners.Name
                                            where DictionaryPartners.View == 1 || DictionaryPartners.Customer == 1
                                            select DictionaryPartners;

            WorksCurrencySalesList3.ItemsSource = from DictionaryCurrencies in database.DictionaryCurrencies
                                                 orderby DictionaryCurrencies.Name
                                                 where DictionaryCurrencies.View == 1
                                                 select DictionaryCurrencies;

            WorksCustomerCommissionList3.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                                      orderby DictionaryPartners.Name
                                                      where DictionaryPartners.View == 1 || DictionaryPartners.CustomerCommission == 1
                                                      select DictionaryPartners;

            WorksProjectList3.ItemsSource = from DictionaryProjects in database.DictionaryProjects
                                           orderby DictionaryProjects.Name
                                           where DictionaryProjects.View == 1
                                           select DictionaryProjects;

            //Справочники для полей типа ComboBox таблицы Works4 - Услуги

            WorksOperTypeList4.ItemsSource = from DictionaryOperTypes in database.DictionaryOperTypes
                                             where DictionaryOperTypes.Id == 4
                                             orderby DictionaryOperTypes.Name
                                             select DictionaryOperTypes;

            WorksCustomerList4.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                             orderby DictionaryPartners.Name
                                             where DictionaryPartners.View == 1 || DictionaryPartners.Customer == 1
                                             select DictionaryPartners;

            WorksCurrencySalesList4.ItemsSource = from DictionaryCurrencies in database.DictionaryCurrencies
                                                  orderby DictionaryCurrencies.Name
                                                  where DictionaryCurrencies.View == 1
                                                  select DictionaryCurrencies;

            WorksCustomerCommissionList4.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                                       orderby DictionaryPartners.Name
                                                       where DictionaryPartners.View == 1 || DictionaryPartners.CustomerCommission == 1
                                                       select DictionaryPartners;

            WorksProjectList4.ItemsSource = from DictionaryProjects in database.DictionaryProjects
                                            orderby DictionaryProjects.Name
                                            where DictionaryProjects.View == 1
                                            select DictionaryProjects;

            //Справочники для полей типа ComboBox таблицы Works - Закладка "Техн. режим
            
            WorksOperTypeList9.ItemsSource = from DictionaryOperTypes in database.DictionaryOperTypes
                                             orderby DictionaryOperTypes.Name
                                             select DictionaryOperTypes;

            WorksLoadingPlaceList9.ItemsSource = database.DictionaryPlaces; //Можно выбрать значение NULL в ComboBox
            
            WorksUnloadingPlaceList9.ItemsSource = database.DictionaryPlaces; //Можно выбрать значение NULL в ComboBox

            WorksMachineList9.ItemsSource = database.DictionaryMachines; //Можно выбрать значение NULL в ComboBox

            WorksDriverList9.ItemsSource = database.DictionaryDrivers;  //Можно выбрать значение NULL в ComboBox

            WorksGoodsList9.ItemsSource = database.DictionaryGoods;  //Можно выбрать значение NULL в ComboBox

            WorksSupplierList9.ItemsSource = database.DictionaryPartners; //Можно выбрать значение NULL в ComboBox

            WorksCurrencyPurchasingList9.ItemsSource = database.DictionaryCurrencies; //Можно выбрать значение NULL в ComboBox

            WorksSupplierCommissionList9.ItemsSource = database.DictionaryPartners; //Можно выбрать значение NULL в ComboBox

            WorksCustomerList9.ItemsSource = database.DictionaryPartners; //Можно выбрать значение NULL в ComboBox

            WorksCurrencySalesList9.ItemsSource = database.DictionaryCurrencies; //Можно выбрать значение NULL в ComboBox

            WorksCustomerCommissionList9.ItemsSource = database.DictionaryPartners; //Можно выбрать значение NULL в ComboBox

            WorksProjectList9.ItemsSource = from DictionaryProjects in database.DictionaryProjects
                                           orderby DictionaryProjects.Name
                                           where DictionaryProjects.View == 1
                                           select DictionaryProjects;

            //Справочники для полей типа ComboBox таблицы Transactions - Закладка "Финансы"
            
            TransactionsTypeList.ItemsSource = from DictionaryTransactionTypes in database.DictionaryTransactionTypes
                                               orderby DictionaryTransactionTypes.Name
                                               select new
                                                   {
                                                       Id = DictionaryTransactionTypes.Id,
                                                       Name = DictionaryTransactionTypes.Name
                                                   };

            TransactionsCurrencyList.ItemsSource = from DictionaryCurrencies in database.DictionaryCurrencies
                                                   orderby DictionaryCurrencies.Name
                                                   where DictionaryCurrencies.View == 1
                                                   select new
                                                   {
                                                       Id = DictionaryCurrencies.Id,
                                                       ShortName = DictionaryCurrencies.ShortName
                                                   };
            
            TransactionsCategoryList.ItemsSource = from DictionaryCategories in database.DictionaryCategories
                                                   orderby DictionaryCategories.DictionaryTransactionType.Id
                                                   where DictionaryCategories.View == 1
                                                   select new
                                                   { 
                                                       Id = DictionaryCategories.Id,
                                                       Name = DictionaryCategories.Name + " (" + DictionaryCategories.DictionaryTransactionType.Name + ")" 
                                                   };
            
            TransactionsPartnerList.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                                  orderby DictionaryPartners.Name
                                                  where DictionaryPartners.View == 1 || DictionaryPartners.FinPartner == 1
                                                  select DictionaryPartners;

            TransactionsDriverList.ItemsSource = from DictionaryDrivers in database.DictionaryDrivers
                                                 orderby DictionaryDrivers.Name
                                                 where DictionaryDrivers.View == 1
                                                 select DictionaryDrivers;
            
            TransactionsProjectList.ItemsSource = from DictionaryProjects in database.DictionaryProjects
                                                  orderby DictionaryProjects.Name
                                                  where DictionaryProjects.View == 1
                                                  select DictionaryProjects;

            //Список типов транзакций для справочника категорий
            DictionaryCategoriesTypeList.ItemsSource = database.DictionaryTransactionTypes;

            //Параметры диапазона дат для конструктора
            DateTime varFinFromDate;
            DateTime varFinToDate;
            DateTime varWorkFromDate;
            DateTime varWorkToDate;
            GetSetDataRepConstructor(out varFinFromDate, out varFinToDate, out varWorkFromDate, out varWorkToDate);
   
            //CheckDateParam(varFinFromDate, varFinToDate, varWorkFromDate, varWorkToDate);

            WorkReportConstructor(varWorkFromDate, varWorkToDate);
            FinanceReportConstructor(varFinFromDate, varFinToDate);
            FuelConstructor(varFinFromDate, varFinToDate);

            //Reports Kassa
            Kassa.ItemsSource = database.ExecuteStoreQuery<KassaObject>(KassaObject.sql);
            
            //Reports Store
            Store.ItemsSource = database.ExecuteStoreQuery<StoreObject>(StoreObject.sql);
            //Reports FuelSupplier
            FuelSupplier.ItemsSource = database.ExecuteStoreQuery<FuelSupplierObject>(FuelSupplierObject.sql);
            //Reports FuelTotal
            FuelTotal.ItemsSource = database.ExecuteStoreQuery<FuelTotalObject>(FuelTotalObject.sql);
            //Reports FuelProjects
            FuelProjects.ItemsSource = database.ExecuteStoreQuery<FuelProjectsObject>(FuelProjectsObject.sql);
            //Reports FuelGasStations
            FuelGasStations.ItemsSource = database.ExecuteStoreQuery<FuelGasStationsObject>(FuelGasStationsObject.sql);
            
            //Reports FuelMachinas
            FuelMachinas.ItemsSource = database.ExecuteStoreQuery<FuelMachinasObject>(FuelMachinasObject.sql);
            //Reports FuelMachinas2
            FuelMachinas2.ItemsSource = database.ExecuteStoreQuery<FuelMachinas2Object>(FuelMachinas2Object.sql);

            //Reports Receivables
            Receivables.ItemsSource = database.ExecuteStoreQuery<ReceivablesObject>(ReceivablesObject.sql);
            //Reports Payables
            Payables.ItemsSource = database.ExecuteStoreQuery<PayablesObject>(PayablesObject.sql);
            //Reports Categories
            ReportCategories.ItemsSource = database.ExecuteStoreQuery<ReportCategoriesObject>(ReportCategoriesObject.sql);
            //Reports Procent
            ReportProcent.ItemsSource = database.ExecuteStoreQuery<ProcentObject>(ProcentObject.sql);
            //Reports Nalog
            ReportNalog.ItemsSource = database.ExecuteStoreQuery<ReportNalogObject>(ReportNalogObject.sql);
            //Reports Dolg
            ReportDolg.ItemsSource = database.ExecuteStoreQuery<ReportDolgObject>(ReportDolgObject.sql);
            //Report Error
            ReportError.ItemsSource = database.ExecuteStoreQuery<ReportErrorObject>(ReportErrorObject.sql);
            //Reports Receivables NEW
            ReceivablesNew.ItemsSource = database.ExecuteStoreQuery<ReceivablesObjectNew>(ReceivablesObjectNew.sql);
            //Reports Payables NEW
            PayablesNew.ItemsSource = database.ExecuteStoreQuery<PayablesObjectNew>(PayablesObjectNew.sql);
            //Reports Зарплата водителя
            ReportZPVoditel.ItemsSource = database.ExecuteStoreQuery<ReportZPVoditelObject>(ReportZPVoditelObject.sql);
            //Reports Комиссии
            ReportComission.ItemsSource = database.ExecuteStoreQuery<ReportComissionObject>(ReportComissionObject.sql);

            VersionDBDataGrid.ItemsSource = from t in database.VersionDBs
                                            orderby t.Id
                                            select new
                                            { Id = t.Id,
                                            Версия = t.Version,
                                            Дата_обновления = t.Data };
            ShowWhatsNew();
            ReportErrors();
        }

        //Получение диапазона дат для конструктора
        public void GetSetDataRepConstructor(out DateTime varFinFromDate, out DateTime varFinToDate, out DateTime varWorkFromDate, out DateTime varWorkToDate)
        {
            varFinFromDate = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_FinFromDate).First().FinFromDate; ;
            varFinToDate = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_FinToDate).First().FinToDate;
            varWorkFromDate = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_WorkFromDate).First().WorkFromDate; ;
            varWorkToDate = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_WorkToDate).First().WorkToDate;
        }

        //Проверка версии БД и обновление
        public void CheckVersionBD()
        {
            var resultCheckingTableVersionDB = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_CheckingTableVersionDB).First().CheckingTableVersionDB;
            if (resultCheckingTableVersionDB == 0)
            {
                //Вывод сообщения про отсутствие таблицы VersionDB
                resultCheckingTableVersionDB = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_CheckingTableVersionDB).First().CheckingTableVersionDB;
            }
            if (resultCheckingTableVersionDB == 1)
            {
                var versionDB = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_MaxVersionDB).First().MaxVersionDB;
                if (versionDB == 00)
                {
                    MessageBox.Show("Сейчас будет выполнено обновление БД до верcии 10");
                    new vbs_close().RunScript(Properties.Resources.AppTransBackup);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_insert_set1);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_insert_set2);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_insert_set3);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_insert_set4);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_InsertVersion10);
                    versionDB = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_MaxVersionDB).First().MaxVersionDB;
                    InitializeData();
                    InstructionCommandBinding_Executed(null, null);
                }
                //if (versionDB == 10)
                //{
                //    //MessageBox.Show("Сейчас будет выполнено обновление БД до версии 20./nСделайте резервную копию!");
                //    new vbs_close().RunScript(Properties.Resources.AppTransBackup);
                //};
                if (versionDB == 10)
                {
                    //MessageBox.Show("Сейчас будет выполнено обновление БД до версии 20. /n Сделайте резервную копию!");
                    //Запуск vbs скрsипта для резервного копирования БД
                    //new vbs_close().RunScript(Properties.Resources.AppTransBackup);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_1);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_2);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_3);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_4);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_5);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_6);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_7);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_8);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_9);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_10);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_11);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_12);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_13);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_14);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_15);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_16);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_17);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_18);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_19);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_20);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_21);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_22);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_23);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_24);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_25);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_26);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_27);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_28);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_29);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_30);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_31);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_32);
                    versionDB = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_MaxVersionDB).First().MaxVersionDB;
                    InitializeData();
                    InstructionCommandBinding_Executed(null, null);
                }
                if (versionDB == 20)
                {
                    //MessageBox.Show("Сейчас будет выполнено обновление БД до версии 30. /n Сделайте резервную копию!");
                    //Запуск vbs скрsипта для резервного копирования БД
                    //new vbs_close().RunScript(Properties.Resources.AppTransBackup);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_1);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_2);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_3);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_4);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_5);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_6);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_7);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_8);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_9);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_10);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_11);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_12);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_13);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_14);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_15);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_16);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_17);
                        //database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_18);

                    //    versionDB = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_MaxVersionDB).First().MaxVersionDB;
                    //    InitializeData();
                    //    InstructionCommandBinding_Executed(null, null);
                    //}

                    //if (versionDB == 30)
                    //{
                    //    //MessageBox.Show("Сейчас будет выполнено обновление БД до версии 35. /n Сделайте резервную копию!");
                    //    //Запуск vbs скрsипта для резервного копирования БД
                    //    //new vbs_close().RunScript(Properties.Resources.AppTransBackup);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v35_1);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v35_2);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v35_3);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v35_4);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v35_5);
                    //database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v35_6);
                    //database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v35_7);
                    //database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v35_8);
                    //database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v35_9);
                    //database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v35_10);
                    //database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v35_11);
                    //database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v35_12);
                    //database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v35_13);

                    versionDB = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_MaxVersionDB).First().MaxVersionDB;
                    InitializeData();
                    InstructionCommandBinding_Executed(null, null);
                }
            }
        }

        /// <summary>
        /// Подготовка данных для конструктора "Работы"
        /// </summary>
        private void WorkReportConstructor(DateTime? fromDate = null, DateTime? toDate = null)
        {
            if (fromDate == null) fromDate = DateTime.MinValue;
            if (toDate == null) toDate = DateTime.MaxValue;
            WorksRep.ItemsSource = from work in database.Works
                                   where work.Date >= fromDate &&
                                         work.Date <= toDate
                                   orderby work.Date
                                   select new
                                   {
                                       Дата = work.Date,
                                       Месяц = work.Date.Month,
                                       Год = work.Date.Year,
                                       ТипРаб = work.DictionaryOperType.Name,
                                       МестоЗагр = work.DictionaryPlace.Name,
                                       МестоРазгр = work.DictionaryPlace1.Name,
                                       Машина = work.DictionaryMachine.Name,
                                       Водитель = work.DictionaryDriver.Name,
                                       ЗарплВодит = work.SalaryDriver,
                                       Груз = work.DictionaryGood.Name,
                                       Вес = work.Weight,
                                       Км = work.Distance,
                                       КолРаб = work.CountWork,
                                       Поставщик = work.DictionaryPartner2.Name, //Всегда проверять номер связи в db_trans3.edmx
                                       СуммаЗакупки = work.PriceOfPurchasing,
                                       ВалютаЗакупки = work.DictionaryCurrency.ShortName, //Всегда проверять номер связи в db_trans3.edmx
                                       КомиссионерПоставщика = work.DictionaryPartner3.Name, //Всегда проверять номер связи в db_trans3.edmx
                                       СуммаКомисПоставщика = work.PriceCommissionPurchase,
                                       Заказчик = work.DictionaryPartner.Name, //Всегда проверять номер связи в db_trans3.edmx
                                       СуммаПродажи = work.PriceOfSales,
                                       ВалютаПродажи = work.DictionaryCurrency1.ShortName,
                                       КомиссионерЗаказч = work.DictionaryPartner1,
                                       СуммаКомисЗаказч = work.PriceCommissionSales,
                                       Проект = work.DictionaryProject.Name,
                                       Описание = work.Discription
                                   };
            //WorksRepNew.ItemsSource = from work in database.Works
            //                          where work.Date >= fromDate &&
            //                                work.Date <= toDate
            //                          orderby work.Date
            //                          select new
            //                          {
            //                              Дата = work.Date,
            //                              Месяц = work.Date.Month,
            //                              Год = work.Date.Year,
            //                              ТипРаб = work.DictionaryOperType.Name,
            //                              МестоЗагр = work.DictionaryPlace.Name,
            //                              МестоРазгр = work.DictionaryPlace1.Name,
            //                              Машина = work.DictionaryMachine.Name,
            //                              Водитель = work.DictionaryDriver.Name,
            //                              ЗарплВодит = work.SalaryDriver,
            //                              ИтогЗарплВодит = work.SalaryDriver * work.CountWork,
            //                              Груз = work.DictionaryGood.Name,
            //                              Вес = work.Weight,
            //                              ИтогВес = work.Weight * work.CountWork,
            //                              Км = work.Distance,
            //                              ИтогКм = work.Distance * work.CountWork,
            //                              КолРаб = work.CountWork,
            //                              Поставщик = work.DictionaryPartner.Name,
            //                              СуммаЗакупки = work.PriceOfPurchasing,
            //                              ИтогСуммаЗакупки = work.PriceOfPurchasing * work.CountWork,
            //                              ВалютаЗакупки = work.DictionaryCurrency.ShortName,
            //                              КомиссионерПоставщика = work.DictionaryPartner1.Name,
            //                              СуммаКомисПоставщика = work.PriceCommissionPurchase,
            //                              ИтогСуммаКомисПоставщика = work.PriceCommissionPurchase * work.CountWork,
            //                              Заказчик = work.DictionaryPartner2.Name,
            //                              СуммаПродажи = work.PriceOfSales,
            //                              ИтогСуммаПрод = work.PriceOfSales * work.CountWork,
            //                              ВалютаПродажи = work.DictionaryCurrency1.ShortName,
            //                              КомиссионерЗаказч = work.DictionaryPartner3,
            //                              СуммаКомисЗаказч = work.PriceCommissionSales,
            //                              ИтогСуммаКомисЗаказч = work.PriceCommissionSales * work.CountWork,
            //                              Проект = work.DictionaryProject.Name,
            //                              Описание = work.Discription
            //                          };
        }

        /// <summary>
        /// Подготовка данных для конструктора "Финансы"
        /// </summary>
        private void FinanceReportConstructor(DateTime? fromDate = null, DateTime? toDate = null)
        {
            if (fromDate == null) fromDate = DateTime.MinValue;
            if (toDate == null) toDate = DateTime.MaxValue;
            FinRep.ItemsSource = from Transactions in database.Transactions
                                 where Transactions.Date >= fromDate &&
                                       Transactions.Date <= toDate
                                 orderby Transactions.Date
                                 select new
                                 {
                                     Дата = Transactions.Date,
                                     Месяц = Transactions.Date.Month,
                                     Год = Transactions.Date.Year,
                                     Тип = Transactions.DictionaryTransactionType.Name,
                                     Сумма = Transactions.Summa,
                                     Валюта = Transactions.DictionaryCurrency.ShortName,
                                     Категория = Transactions.DictionaryCategory.Name,
                                     Партнер = Transactions.DictionaryPartner.Name,
                                     Водитель = Transactions.DictionaryDriver.Name,
                                     Литры = Transactions.Liters,
                                     Проект = Transactions.DictionaryProject.Name
                                 };
        }

        /// <summary>
        /// Подготовка данных для конструктора "Учет топлива"
        /// </summary>
        private void FuelConstructor(DateTime? fromDate = null, DateTime? toDate = null)
        {
            if (fromDate == null) fromDate = DateTime.MinValue;
            if (toDate == null) toDate = DateTime.MaxValue;
            FuelRep.ItemsSource = from Refuelings in database.Refuelings
                                  where Refuelings.Date >= fromDate &&
                                        Refuelings.Date <= toDate
                                  orderby Refuelings.Date
                                 select new
                                 {
                                     Дата = Refuelings.Date,
                                     Месяц = Refuelings.Date.Month,
                                     Год = Refuelings.Date.Year,
                                     ВидЗаправки = Refuelings.DictionaryFuelOperType.Name,
                                     Партнер = Refuelings.DictionaryPartner.Name,
                                     ТопливоСправочн = Refuelings.DictionaryFuelType.Name,
                                     Машина = Refuelings.DictionaryMachine.Name,
                                     Водитель = Refuelings.DictionaryDriver.Name,
                                     Литры = Refuelings.Liters,
                                     Сумма = Refuelings.Price,
                                     ОстатокВбаке = Refuelings.FuelRemaining,
                                     ПробегGPS = Refuelings.Distance,
                                     Одометр = Refuelings.Odometer,
                                     ТопливоКатегор = Refuelings.DictionaryCategory.Name,
                                     АЗС_Карта = Refuelings.DictionaryGasStation.Name,
                                     Проект = Refuelings.DictionaryProject.Name
                                 };
        }

        /// <summary>
        /// Уведомление про найденные ошибки
        /// </summary>
        private void ReportErrors()
        {
            var reportErrors = database.ExecuteStoreQuery<ReportErrorObject>(ReportErrorObject.sql);
            var i = 0;
            foreach (var reportError in reportErrors)
            {
                var errorsCountString = reportError.Кол_во_ошибок;
                var levelErrorsString = reportError.Уровень_ошибки;
                var errorsCount = 0;
                int.TryParse(errorsCountString, out errorsCount);

                if (errorsCount > 0 && levelErrorsString == "Критичный")
                {
                    i += errorsCount;
                }
            }
            if (i > 0)
            {
                MessageBox.Show("Найдены критические ошибки.\nПроверьте отчет Настройки --> Ошибки!\nКол-во критических ошибок = " + i, "Внимание, найдены ошибки!", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }

        private void CheckErrors()
        {
            var reportErrors = database.ExecuteStoreQuery<ReportErrorObject>(ReportErrorObject.sql);
                int critical = 0;
                int warning = 0;
                int info = 0;
            foreach (var reportError in reportErrors)
            {
                var errorsCountString = reportError.Кол_во_ошибок;
                var levelErrorsString = reportError.Уровень_ошибки;
                var errorsCount = 0;

                int.TryParse(errorsCountString, out errorsCount);

                if (errorsCount > 0 && levelErrorsString == "Критичный")
                {
                    critical += errorsCount;
                }
                if (errorsCount > 0 && levelErrorsString == "Предупреждение")
                {
                    warning += errorsCount;
                }
                if (errorsCount > 0 && levelErrorsString == "Информационный")
                {
                    info += errorsCount;
                }
            }                
            MessageBox.Show("Кол-во критических ошибок = " + critical + "\nКол-во предупреждений = " + warning + "\nКол-во информационных сообщений = " + info, "Проверка на ошибки", MessageBoxButton.OK, MessageBoxImage.Warning);            
        }

        private void ShowWhatsNew()
        {
            //Проверка флага ShowWhatsNew
            var ShowWhatsNew = RegistryKeyValues.GetValue("ShowWhatsNew");
  
            if ((string)ShowWhatsNew == null)
            {
                RegistryKeyValues.SetValue("ShowWhatsNew", "0");
            }

            if ((string)ShowWhatsNew == "0")
            {
                //MessageBox.Show("ShowWhatsNew == 1");
                InstructionCommandBinding_Executed(null, null);
                RegistryKeyValues.SetValue("ShowWhatsNew", "1");
            }
        }

        #region Events
        /// <summary>
        /// Были ли изменения в базе
        /// </summary>
        /// <returns>true, если база изменена</returns>
        private bool isDatabaseDirty()
        {
            return database.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified).Any();
        }

        private bool TryToSave()
        {
            try
            {
                database.SaveChanges();
            }
            catch (Exception exc)
            {
                StatusBarText.Text = "Ошибка при сохранении в " + DateTime.Now.TimeOfDay;
                MessageBox.Show(exc.InnerException.Message, "Ошибка при сохранении", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }

            return true;
        }

        //Подтверждение при выходи (Сохранить - Да/Нет)
        private bool SaveDataConfirm()
        {
            /// Изменений в базе не было, значит не нужно запрашивать сохранение
            if (!isDatabaseDirty())
                return true;

            if (MessageBox.Show("Сохранить?", "Выход", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                return TryToSave();

            return true;
        }

        void exitCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        void MainWindow_Closing(object sender, CancelEventArgs e)
        {
            var success = SaveDataConfirm();
            if (!success)
                e.Cancel = true;
            new vbs_close().RunScript(Properties.Resources.AppTransBackup);
        }

        void saveCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (TryToSave())
            {
                InitializeData();
                StatusBarText.Text = "Сохранено в " + DateTime.Now.TimeOfDay;
            }
        }

        void CheckErrors_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            CheckErrors();
        }

        void CheckDateParam_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            DateTime varFinFromDate;
            DateTime varFinToDate;
            DateTime varWorkFromDate;
            DateTime varWorkToDate;
            GetSetDataRepConstructor(out varFinFromDate, out varFinToDate, out varWorkFromDate, out varWorkToDate);
            MessageBox.Show("WorkDateFrom =" + varWorkFromDate + "\nWorkDateTo =" + varWorkToDate + "\nFinDateFrom =" + varFinFromDate + "\nFinDateTo =" + varFinToDate);
        }

        void BackupDB_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            new vbs_close().RunScript(Properties.Resources.AppTransBackup);
        }

        void RunSQL_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            byte EnableRunSQL = byte.MinValue;
            EnableRunSQL = byte.Parse(ConfigurationManager.AppSettings["EnableRunSQL"]);
            if (EnableRunSQL == 1)
            {
                ConfigurationManager.AppSettings["EnableRunSQL"] = "2";
                MessageBoxResult show = MessageBox.Show("Значение EnableRunSQL = " + EnableRunSQL);
            }
            if (EnableRunSQL == 2)
            {
                MessageBoxResult show = MessageBox.Show("Значение EnableRunSQL = " + EnableRunSQL);
            }
            else
            {
                MessageBoxResult show = MessageBox.Show("Некорректное значение параметра. \nEnableRunSQL = " + EnableRunSQL);
            }
        }

        void VerDB_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var resultCheckingTableVersionDB2 = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_CheckingTableVersionDB).First().CheckingTableVersionDB;
            var versionDB2 = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_MaxVersionDB).First().MaxVersionDB;
            MessageBox.Show("Наличие таблицы VersionDB: " + resultCheckingTableVersionDB2 +
            "\nТекущая версия БД: " + versionDB2 +
            "\nВход в систему: " + RegistryKeyValues.GetValue("LastStartProgram"), "Версия БД");
        }

        void refreshCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            InitializeData();
            StatusBarText.Text = "Обновлено из базы в " + DateTime.Now.TimeOfDay;
        }

        #region Show windows

        void aboutCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            AboutWindow aboutWindow = new AboutWindow();
            aboutWindow.Show();
        }

        void HotkeysCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            HotkeysWindow HotkeysWindow = new HotkeysWindow();
            HotkeysWindow.Show();
        }

        void InstructionCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            InstructionWindow InstructionWindow = new InstructionWindow();
            InstructionWindow.Show();
        }

        #endregion

        // Клонирование строки - Продажи. Эту операцию можно выполнять только на сохраненной базе.
        private void WorksCloneButton_Click(object sender, RoutedEventArgs e)
        {
            if (isDatabaseDirty())
            {
                MessageBox.Show("Сохраните базу перед продолжением", "Clone", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                return;
            }

            Work work = WorksDataGrid.SelectedItem as Work;
            if (work == null)
                return;

            database.Detach(work);
            database.Works.AddObject(work);

            work.Date = DateTime.Now;
            work.Weight = 0;
            work.PriceOfSales = 0;
            work.Discription = null;

            TryToSave();
            InitializeData();
        }

        // Клонирование строки - Перевозки. Эту операцию можно выполнять только на сохраненной базе.
        private void WorksCloneButton_Click2(object sender, RoutedEventArgs e)
        {
            if (isDatabaseDirty())
            {
                MessageBox.Show("Сохраните базу перед продолжением", "Clone", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                return;
            }

            Work work = WorksDataGrid2.SelectedItem as Work;
            if (work == null)
                return;

            database.Detach(work);
            database.Works.AddObject(work);

            work.Date = DateTime.Now;
            work.Weight = 0;
            work.PriceOfSales = 0;
            work.Discription = null;

            TryToSave();
            InitializeData();
        }
        #endregion
    }
}
